package com.biwei.app.wrap.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.connector.ResponseFacade;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JsonUtil {

    public static void writeResponse(Object value, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = SpringContextHolder.getBean(ObjectMapper.class);
        if (value instanceof String) {
            writeResponse((String) value, response);
        } else
            writeResponse(objectMapper.writeValueAsString(value), response);
    }

    public static void writeResponse(String value, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (!StringUtils.isEmpty(value)) {
            response.getWriter().print(value);
        }
    }

    public static <T> T readValue(String value, Class<T> clazz) throws IOException {
        ObjectMapper objectMapper = SpringContextHolder.getBean(ObjectMapper.class);
        return objectMapper.readValue(value, clazz);
    }
    public static String writeValueAsString(Object object) throws JsonProcessingException {
        ObjectMapper objectMapper = SpringContextHolder.getBean(ObjectMapper.class);
        return objectMapper.writeValueAsString(object);
    }
}
